#include "factory.h"

int main(int argc,char** argv)
{
    if(argc!=3)
    {
        printf("/thread_pool_server IP PORT\n");
        return -1;
    }
    ARGS_CHECK(argc,3);
    int sfd;
    sfd=socket(AF_INET,SOCK_STREAM,0);//初始化一个网络描述符，对应了一个缓冲区
    ERROR_CHECK(sfd,-1,"socket");
    printf("sfd=%d\n",sfd);
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));//清空
    ser_addr.sin_family=AF_INET;//代表要进行ipv4通信
    ser_addr.sin_addr.s_addr=inet_addr(argv[1]);//把ip的点分十进制转为网络字节序
    ser_addr.sin_port=htons(atoi(argv[2]));//把端口转为网络字节序
    //客户端就要去连接服务器
    int ret=connect(sfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr));
    ERROR_CHECK(ret,-1,"connect");
    struct epoll_event evs[2];
    //epoll注册监控sfd,STDIN_FILENO
    int epfd=epoll_create(1);
    epoll_add(epfd,STDIN_FILENO);
    epoll_add(epfd,sfd);
    Factory_t f;//主数据结构
    int thread_num=THREAD_NUM;//子线程数量
    int capacity=CAPACITY;//队列容量
    factory_init(&f,thread_num,capacity);//线程池初始化
    factory_start(&f,thread_num);//启动线程池
    Client_State_t* pnew;
    pQue_t pq=&f.que;//让一个队列指针指向队列
    char c_cmd[128]={0};
    char info[128]={0};
    command_options();
    int ready_fd_num,i,j;
    while(1)
    {
        ready_fd_num=epoll_wait(epfd,evs,2,-1);//等待描述符就绪，哪个描述符就绪，epoll就会返回
        for(i=0;i<ready_fd_num;i++)
        {
            if(evs[i].data.fd==STDIN_FILENO)//标准输入可读
            {
                bzero(c_cmd,sizeof(c_cmd));
                ret=read(STDIN_FILENO,c_cmd,sizeof(c_cmd));
                ERROR_CHECK(ret,-1,"read");
                if(!strncmp("cd",c_cmd,2)||!strncmp("ls",c_cmd,2)||!strncmp("remove",c_cmd,6)||!strncmp("pwd",c_cmd,3))
                {
                    printf("----\n");
                    ret=send_n(sfd,c_cmd,strlen(c_cmd)-1);//向对方发送数据，不带\n
                    ERROR_CHECK(ret,-1,"send_n");
                }
                else if(!strncmp("puts",c_cmd,4)||!strncmp("gets",c_cmd,4)){
                    pnew=(Client_State_t*)calloc(1,sizeof(Client_State_t));//申请空间
                    //pnew放入队列
                    pnew->sfd=sfd;
                    pthread_mutex_lock(&pq->mutex);//加锁
                    que_set(pq,pnew);//放入队列
                    pthread_mutex_unlock(&pq->mutex);//解锁
                    pthread_cond_signal(&f.cond);//使条件成立
                    ret=send_n(sfd,c_cmd,strlen(c_cmd)-1);//向对方发送数据，不带\n
                    ERROR_CHECK(ret,-1,"send_n");
                }
                else{
                    printf("Invalid inputs\n");
                }
            }
            if(evs[i].data.fd==sfd)//如果sfd可读
            {
                int c_cmd_len;
                bzero(info,sizeof(info));
                ret=recv_n(sfd,&c_cmd_len,sizeof(int));//接收服务器端发送的火车头
                ERROR_CHECK(ret,-1,"recv_n");
                ret=recv_n(sfd,info,c_cmd_len);//接收服务器端发送的火车厢
                ERROR_CHECK(ret,-1,"recv_n");
                printf("%s\n",info);
            }    
        }
    }
    close(sfd);
}